import Vue from "vue";
import Router from "vue-router";
import store from '@/store';
import {
  sessionStorage,
  hasPermission
} from "@/utils";
import {
  BASE_ROUTES
} from "@/router/routes";

Vue.use(Router);

// 配置路由权限
let router = new Router({
  routes: BASE_ROUTES,
  scrollBehavior() {
    return {
      x: 0,
      y: 0
    };
  }
});

router.beforeEach((to, from, next) => {
  // 设置title
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  // 登录
  let user = sessionStorage.get("USER") || {};
  if (to.name === "login") {
    if (from.name) {
      // 重置路由
      location.reload();
    } else {
      next();
    }
  } else {
    if (user.token) {
      if (to.meta && to.meta.permission && !hasPermission([to.meta.permission])) {
        next({
          name: "forbidden"
        });
      } else {
        // 刷新
        if (!store.state.ROUTES.length && to.name !== "jump") {
          store.commit("SET_DYNAMIC_ROUTES", router);
          next({
            path: to.path,
            query: to.query
          });
        } else {
          next();
        }
      }
    } else {
      next({
        name: "login"
      });
    }
  }
});

export default router;